package com.slt.android.customview;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by dp on 2017/12/14.
 */

public class CustomViewMesure extends View {
    public CustomViewMesure(Context context) {
        super(context);
    }

    public CustomViewMesure(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomViewMesure(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(measureWidth(widthMeasureSpec) , measureHeight(heightMeasureSpec));
    }

    private int measureHeight(int widthMeasureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(widthMeasureSpec);
        int specSize = MeasureSpec.getSize(widthMeasureSpec);

        if(specMode == MeasureSpec.EXACTLY){
            //指出确定值
            //matchParent时
            result = specSize;
        }else {
            result = 200;
            if(specMode == MeasureSpec.AT_MOST){
                //AT_MOST == wrapContent时
                result = Math.min(specSize , result);
            }
        }
        return result;
    }

    private int measureWidth(int heightMeasureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(heightMeasureSpec);
        int specSize = MeasureSpec.getSize(heightMeasureSpec);

        if(specMode == MeasureSpec.EXACTLY){
            //指出确定值
            //matchParent时
            result = specSize;
        }else {
            result = 200;
            if(specMode == MeasureSpec.AT_MOST){
                //AT_MOST == wrapContent时
                result = Math.min(specSize , result);
            }
        }
        return result;
    }
}
